package com.triple.triplerpc.bootstrap;

import com.triple.triplerpc.RpcApplication;
import com.triple.triplerpc.config.RegistryConfig;
import com.triple.triplerpc.config.RpcConfig;
import com.triple.triplerpc.model.ServiceMetaInfo;
import com.triple.triplerpc.model.ServiceRegisterInfo;
import com.triple.triplerpc.registry.LocalRegistry;
import com.triple.triplerpc.registry.Registry;
import com.triple.triplerpc.registry.RegistryFactory;
import com.triple.triplerpc.server.tcp.VertxTcpServer;

import java.util.List;

/**
 * 服务提供者启动类（初始化）
 */
public class ProviderBootstrap {

    /**
     * 初始化
     */
    public static void init(List<ServiceRegisterInfo<?>> serviceRegisterInfoList) {
        // 初始化 RPC 框架
        System.out.println("1. 加载 RPC 配置对象");
        RpcApplication.init();
        final RpcConfig rpcConfig = RpcApplication.getRpcConfig();
        System.out.println("2. RPC 配置初始化为: " + rpcConfig);

        for (ServiceRegisterInfo<?> serviceRegisterInfo : serviceRegisterInfoList) {
            // 注册服务到本地服务注册器, 用于获取方法的实现类
            String serviceName = serviceRegisterInfo.getServiceName();
            LocalRegistry.register(serviceName, serviceRegisterInfo.getImplClass());
            System.out.println("3. 注册服务到本地服务注册器: {" + serviceName + ": " + LocalRegistry.get(serviceName) + "}");

            // 注册服务到注册中心
            RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
            Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry()); // SPI 机制获取注册中心对象实例
            ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo(); // 构造服务的注册信息
            serviceMetaInfo.setServiceName(serviceName);
            serviceMetaInfo.setServiceHost(rpcConfig.getServerHost());
            serviceMetaInfo.setServicePort(rpcConfig.getServerPort());
            try {
                registry.register(serviceMetaInfo); // 注册服务
            } catch (Exception e) {
                throw new RuntimeException(serviceName + " 服务注册失败", e);
            }
            System.out.println("4. 注册服务到注册中心: " + serviceMetaInfo);
        }

        System.out.println("5. 启动 Web 服务");
        /** 启动 HTTP 服务
         HttpServer httpServer = new VertxHttpServer();
         httpServer.doStart(RpcApplication.getRpcConfig().getServerPort());
         System.out.println("6. HTTP 服务器启动成功, 监听端口: " + RpcApplication.getRpcConfig().getServerPort());
         */
        // 启动 TCP 服务
        VertxTcpServer vertxTcpServer = new VertxTcpServer();
        vertxTcpServer.doStart(rpcConfig.getServerPort());
        System.out.println("6. TCP 服务器启动成功, 监听端口: " + rpcConfig.getServerPort());
    }

}
